<!-- 新增与编辑仓库 -->
<template>
  <el-dialog
    :title="dialog.title"
    :visible.sync="dialog.show"
    width="1030px"
    height="500px"
    style="margin-top: -100px;"
    append-to-body
    @close="handleClose"
  >
    <div class="dialog-content">
      <!-- 头部 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="师傅信息" name="first" style="height:480px; overflow: auto; width: 100%;">
          <el-form ref="form1" :model="form" :rules="rules" label-width="150px">

            <div style="display: inline-block; width: 100%;">
              <!--              style="width: 50%; float: left;"-->
              <div>
                <span class="title">基本信息</span>
                <el-form-item class="title-input" prop="maintainSiteContact" label="师傅姓名:">
                  <!--                  <span style="color:red">*</span>&nbsp;-->
                  <el-input v-model="form.maintainSiteContact"/>
                </el-form-item>
                <el-form-item label="手机号:" prop="maintainSiteMobile">
                  <!--                  <span style="color:red">*</span>&nbsp;-->
                  <el-input v-model="form.maintainSiteMobile"/>
                </el-form-item>
                <el-form-item label="登录密码:" prop="password">
                  <!--                  <span style="color:red">*</span>&nbsp;-->
                  <el-input v-model="form.password" placeholder="不输入则使用现有密码"/>
                </el-form-item>
              </div>

              <div>
                <span class="title">其他信息</span>
                <el-form-item label="师傅级别:" prop="maintainWorkerLevel">
                  <!--                  <span style="color:red">*</span>&nbsp;-->
                  <el-select v-model="form.maintainWorkerLevel" placeholder="请选择师傅级别" class="seach-select" size="small">
                    <el-option
                      v-for="item in form.type_options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="合作状态:" prop="maintainSiteCooperation">&nbsp;&nbsp;
                  <el-radio-group v-model="form.maintainSiteCooperation">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>

              <div>
                <span class="title">师傅信息</span>
                <el-form-item label="师傅身份证:" prop="contactIdentification">
                  <!--                  <span style="color:red">*</span>&nbsp;-->
                  <el-input v-model="form.contactIdentification"/>
                </el-form-item>
                <el-form-item label="身份证图片:" prop="contactIdPhoto">&nbsp;&nbsp;
                  <div style="width: 450px; height: 200px; overflow: hidden; margin-top: -25px; margin-left: -18px;">
                    <img :src="form.contactIdPhoto" style="width: 100%; height:100%; margin-left: 15px;">
                  </div>
                </el-form-item>
              </div>

            </div>

          </el-form>
        </el-tab-pane>

        <el-tab-pane label="服务范围" name="second" class="planes">
          <el-tree
            ref="tree"
            :data="treeData"
            :default-expanded-keys="zhankai"
            :default-checked-keys="xuanzhong"
            :props="defaultProps"
            show-checkbox
            node-key="groupId"
            @check-change="nodeClick"/>
        </el-tab-pane>

        <el-tab-pane label="快速服务区域" name="third" class="planes">
          <el-table :data="tableData">
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click.native.prevent="delRow(scope.$index, tableData)">移除</el-button>
                <el-button type="text" size="small" @click="addRow">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="serviceProvince" label="省份">
              <template slot-scope="scope">
                <el-select v-model="scope.row.serviceProvince" placeholder="请选择" @change="selectProvince(scope.$index, scope.row)">
                  <el-option v-for="item in provinceList[scope.$index]" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="serviceCity"
              label="城市">
              <template slot-scope="scope">
                <el-select v-model="scope.row.serviceCity" placeholder="请选择" @change="selectCity(scope.$index, scope.row)">
                  <el-option v-for="item in cityList[scope.$index]" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="serviceCommunity"
              label="社区">
              <template slot-scope="scope">
                <el-select v-model="scope.row.serviceCommunity" placeholder="请选择" @change="selectCommunity(scope.$index, scope.row)">
                  <el-option v-for="item in areaList[scope.$index]" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="serviceStreet"
              label="街道">
              <template slot-scope="scope">
                <el-select v-model="scope.row.serviceStreet" placeholder="请选择" @change="selectStreet(scope.$index, scope.row)">
                  <el-option v-for="item in streetList[scope.$index]" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 主体 -->

      <!-- 底部 -->
      <div class="text-center mt-30">
        <el-button class="greenbt bt-wd" type="primary" @click="saveFun('form1')">保存</el-button>
        <el-button class="greenbt bt-wd" type="info" @click="returnBack()">返回</el-button>
        <el-button class="greenbt bt-wd" type="danger" @click="deleteWorker()">删除师傅</el-button>
      </div>
    </div>

  </el-dialog>
</template>
<style>
  label {
    font-weight: 300 !important;
    color: #666666 !important;
  }
  .planes{
    width: 100%;
    height: 600px;
    overflow:auto;
  }
  el-input {
    width: 250px !important;
  }
  .title{
    color: black; font-weight: 700;
  }
</style>
<script>
// var checkArea = (rule, value, callback) => {
//   if (!value) {
//     callback()
//   } else {
//     const regu = /^[0-9]+(\.[0-9]{1,2})?$/
//     const rsCheck = regu.test(value)
//     if (!rsCheck) {
//       return callback(new Error('格式不正确'))
//     }
//   }
//   callback()
// }
import {
  getWorkInfoById,
  getCategoryGroups,
  getCategoryGroupsById,
  provinces,
  citiesByPid,
  areasByCid,
  streetsByaid,
  serviceAreas,
  saveWorker,
  delWorker
} from '@/api/webpoint/worker'

export default {
  props: {
    // 父组件调用时传进来的参数
    modalStaticData: {
      type: Object,
      default: () => {
      }
    },
    modalData: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      customWidth: 600,
      one: false,
      two: false,
      three: false,
      xuanzhong: [],
      zhankai: [],
      defaultProps: {
        children: 'leafCategoryList',
        label: 'groupName'
      },
      treeData: [],
      tableData: [
        {
          serviceProvince: '',
          serviceCity: '',
          serviceCommunity: '',
          serviceStreet: ''
        }
      ],
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      dialog: {
        title: '修改师傅信息',
        show: true
      },
      activeName: 'first',
      form: {
        password: '',
        // maintainSiteEmail: '', // 邮箱
        contactIdPhoto: '', // 身份证图片
        maintainWorkerPwd: '', // 登录密码
        maintainSiteContact: '', // 师傅名称
        maintainSiteMobile: '', // 手机号
        maintainWorkerLevel: 'worker_level_full-time', // 师傅级别
        maintainSiteCooperation: true, // 合作状态
        contactIdentification: '', // 师傅身份证
        // maintainSiteTelephone: '', // 其他电话
        // maintainSiteProvinceText: '',//省份
        maintainSiteProvinceId: [], // 省份id
        // maintainSiteCityText: '',//城市
        maintainSiteCityId: [], // 城市id
        // maintainSiteCommunityText: '',//区域
        maintainSiteCommunityId: [], // 区域id
        // maintainSiteStreetText: '',//街道
        maintainSiteStreetId: [], // 街道id
        type_options: [
          { label: '全职', value: 'worker_level_full-time' },
          { label: '兼职', value: 'worker_level_part-time' }
        ]
      },
      rules: {
        maintainSiteContact: [{ required: true, message: '请输入师傅名称', trigger: 'blur' }],
        maintainSiteMobile: [{ required: true, message: '请输入师傅手机号', trigger: 'blur' }],
        contactIdentification: [{ required: true, message: '请输入师傅身份证号码', trigger: 'blur' }]
        // area: [{
        //   required: true,
        //   validator: checkArea,
        //   trigger: 'blur'
        // }]
      }
    }
  },
  mounted() {
    /**
       * 获取当前师傅信息
       */
    var param = {
      workerId: this.modalData.data.maintainWorkerId
    }
    getWorkInfoById(param).then(res => {
      const worker = res.data
      this.setWorkerInfo(worker)
    })

    /**
       * 获取所有分类
       * */
    getCategoryGroups().then(res => {
      const treeDatas = res.data
      for (let o = 0; o < treeDatas.length; o++) {
        if (treeDatas[o].leafCategoryList.length > 0) {
          for (let i = 0; i < treeDatas[o].leafCategoryList.length; i++) {
            treeDatas[o].leafCategoryList[i].groupId = treeDatas[o].leafCategoryList[i].categoryId
            treeDatas[o].leafCategoryList[i].groupName = treeDatas[o].leafCategoryList[i].categoryName
          }
        }
      }
      this.treeData = treeDatas
    })

    /**
       * 获取当前师傅拥有的分类
       * */
    getCategoryGroupsById(this.modalData.data.maintainWorkerId).then(res => {
      // 清空数据(分类展开和默认选中的数据)
      this.zhankai = []
      this.xuanzhong = []
      const currentCategory = res.data
      for (let o = 0; o < currentCategory.length; o++) {
        this.xuanzhong.push(currentCategory[o].categoryId)
        this.zhankai.push(currentCategory[o].categoryId)
      }
      console.warn('默认展开' + this.zhankai)
      console.warn('默认选中' + this.xuanzhong)
    })

    /**
       * 快速服务区域
       */
    serviceAreas(this.modalData.data.maintainWorkerId).then(res => {
      this.tableData = res.data
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].serviceProvince ? this.form.maintainSiteProvinceId.push(this.tableData[i].serviceProvince) : null
        this.tableData[i].serviceCity ? this.form.maintainSiteCityId.push(this.tableData[i].serviceCity) : null
        this.tableData[i].serviceCommunity ? this.form.maintainSiteCommunityId.push(this.tableData[i].serviceCommunity) : null
        this.tableData[i].serviceStreet ? this.form.maintainSiteStreetId.push(this.tableData[i].serviceStreet) : null
        // 省市区县查询
        this.together(i)
      }
    })
  },
  methods: {
    together(i) {
      this.getProvince(i).then(() => {
        this.getCitiesByPid(i).then(() => {
          this.getAreasByCid(i).then(() => {
            this.getStreetByAid(i)
          })
        })
      })
    },
    getProvince(i) {
      return provinces().then(res => {
        this.$set(this.provinceList, i, res.data)
      })
    },
    getCitiesByPid(i) {
      return citiesByPid(this.form.maintainSiteProvinceId[i]).then(res => {
        this.$set(this.cityList, i, res.data)
        if (this.one) {
          // this.$set(this.tableData, i, { ...this.tableData[i], serviceCity: this.cityList[i][0].id })
          this.one = false
        }
      })
    },
    getAreasByCid(i) {
      return areasByCid(this.form.maintainSiteCityId[i]).then(res => {
        this.$set(this.areaList, i, res.data)
        if (this.two) {
          // this.$set(this.tableData, i, { ...this.tableData[i], serviceCommunity: this.areaList[i][0].id })
          this.two = false
        }
      })
    },
    getStreetByAid(i) {
      return streetsByaid(this.form.maintainSiteCommunityId[i]).then(res => {
        this.$set(this.streetList, i, res.data)
        if (this.three) {
          // this.$set(this.tableData, i, { ...this.tableData[i], serviceStreet: this.streetList[i][0].id })
          this.three = false
        }
      })
    },
    // 赋值封装
    setWorkerInfo(worker) {
      this.form.maintainSiteContact = worker.maintainWorkerName// 师傅名称
      this.form.maintainSiteMobile = worker.maintainWorkerMobile// 师傅电话
      worker.maintainWorkerCooperation === true ? this.form.maintainSiteCooperation = true : this.form.maintainSiteCooperation = false// 是否合作
      // this.form.maintainSiteEmail = worker.maintainSiteEmail// 邮箱
      // this.form.maintainSiteTelephone = worker.maintainSiteTelephone// 其他手机号
      worker.maintainWorkerLevel ? this.form.maintainWorkerLevel = worker.maintainWorkerLevel : this.form.maintainWorkerLevel// 师傅等级
      this.form.contactIdentification = worker.maintainWorkerIdentification// 师傅身份证
      this.form.contactIdPhoto = worker.maintainWorkerIdPhoto// 师傅身份证反面
    },

    handleClick(tab, event) {
      console.log(tab, event)
    },

    delRow(index, rows) {
      rows.splice(index, 1)
      this.form.maintainSiteProvinceId.splice(index, 1)
    },
    addRow() {
      const areaDto = {}
      this.tableData.push(areaDto)
      this.together(this.tableData.length - 1)
    },
    handleClose() {
      this.$emit('close')
    },
    /**
       * 返回
       */
    returnBack() {
      this.dialog.show = false
    },
    /**
       * 编辑师傅
       */
    saveFun(formName) {
      const self = this
      self.$refs[formName].validate(valid => {
        if (valid) {
          // maintainWorkerPwd: '', // 登录密码
          // maintainWorkerLevel: '', // 师傅级别
          // 师傅基本信息
          const dto = {}
          dto.maintainWorkerCooperation = this.form.maintainSiteCooperation// 是否合作
          dto.maintainWorkerName = this.form.maintainSiteContact// 师傅名称
          dto.maintainWorkerIdentification = this.form.contactIdentification// 师傅身份证
          dto.maintainWorkerMobile = this.form.maintainSiteMobile// 师傅手机号
          // 密码
          const password = this.form.password
          // 师傅等级
          const maintainWorkerLevel = this.form.maintainWorkerLevel
          // 数据范围
          const areaDtos = []
          if (this.form.maintainSiteProvinceId.length > 0) {
            for (let i = 0; i < this.form.maintainSiteProvinceId.length; i++) {
              const AreaDto = {
                serviceProvince: '',
                serviceCity: '',
                serviceCommunity: '',
                serviceStreet: ''
              }
              AreaDto.serviceProvince = this.form.maintainSiteProvinceId[i]
              AreaDto.serviceCity = this.form.maintainSiteCityId[i]
              AreaDto.serviceCommunity = this.form.maintainSiteCommunityId[i]
              AreaDto.serviceStreet = this.form.maintainSiteStreetId[i]
              areaDtos.push(AreaDto)
            }
          }
          // 获取服务区域
          const categorylists = this.nodeClick()
          // 师傅id
          const workerId = this.modalData.data.maintainWorkerId

          const data = {}
          data.dto = JSON.stringify(dto)
          data.areaDtos = JSON.stringify(areaDtos)
          data.categorylists = JSON.stringify(categorylists)
          data.password = password
          data.maintainWorkerLevel = maintainWorkerLevel
          data.workerId = workerId

          console.warn('师傅id' + workerId)
          console.warn(data.dto)
          console.warn(data.maintainWorkerLevel)

          saveWorker(data).then(res => {
            console.warn('进入saveWorker方法')
            console.warn(res)
            if (res.data === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
            } else {
              this.$message.error('操作失败')
            }
          }).finally(() => {
            this.dialog.show = false
            this.modalStaticData.closeChildAndRefresh()
          })
        } else {
          return false
        }
      })
    },
    /**
       * 删除师傅
       */
    deleteWorker() {
      const workerId = this.modalData.data.maintainWorkerId
      console.warn('当前需要删除的师傅的ID为: ' + workerId)
      delWorker(workerId).then(res => {
        console.warn(res)
        if (res.data === 1) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        } else {
          this.$message.error('操作失败')
        }
      }).finally(() => {
        this.dialog.show = false
        this.modalStaticData.closeChildAndRefresh()
      })
    },
    selectProvince(index, data) {
      this.form.maintainSiteProvinceId[index] = data.serviceProvince
      this.together(index)
      this.$set(this.tableData, index, { ...this.tableData[index], serviceCity: '' })
      this.$set(this.tableData, index, { ...this.tableData[index], serviceCommunity: '' })
      this.$set(this.tableData, index, { ...this.tableData[index], serviceStreet: '' })
      this.one = true
    },
    selectCity(index, data) {
      this.form.maintainSiteCityId[index] = data.serviceCity
      this.together(index)
      this.$set(this.tableData, index, { ...this.tableData[index], serviceCommunity: '' })
      this.$set(this.tableData, index, { ...this.tableData[index], serviceStreet: '' })
      this.two = true
    },
    selectCommunity(index, data) {
      this.form.maintainSiteCommunityId[index] = data.serviceCommunity
      this.together(index)
      this.$set(this.tableData, index, { ...this.tableData[index], serviceStreet: '' })
      this.three = true
    },
    selectStreet(index, data) {
      this.form.maintainSiteStreetId[index] = data.serviceStreet
      this.together(index)
    },
    nodeClick() {
      const res = this.$refs.tree.getCheckedNodes()
      let arr = []
      res.forEach((item) => {
        arr.push(item.groupId)
      })
      arr = arr.filter(function(ele, index) {
        return ele !== undefined
      })
      return arr
    }

  }
}
</script>
